using System.Collections.Generic;
using System.Text;

namespace MVP.DataAccess.Test
{
    public class InsertStatementBuilder
    {
        private IDictionary<string, Parameter> parameters;
        private string tableName;

        public InsertStatementBuilder(string tableName)
        {
            this.tableName = tableName;
            this.parameters = new Dictionary<string, Parameter>();
        }

        public IList<Parameter> Parameters
        {
            get { return new List<Parameter>(this.parameters.Values); }
        }

        public string TableName
        {
            get { return tableName; }
        }

        public void AddParameter(string name, object value)
        {
            parameters[name] = new Parameter(name, value);
        }

        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("INSERT INTO {0} ({1}) VALUES ({2});", tableName, GetParameterNames(string.Empty),
                                 GetParameterNames("@"));

            return builder.ToString();
        }

        private string GetParameterNames(string prefix)
        {
            StringBuilder builder = new StringBuilder();

            foreach (Parameter parameter in parameters.Values)
            {
                builder.AppendFormat("{0}{1},", prefix, parameter.Name);
            }
            builder.Remove(builder.Length - 1, 1);

            return builder.ToString();
        }

        public class Parameter
        {
            private string name;
            private object value;

            public Parameter(string name, object value)
            {
                this.name = name;
                this.value = value;
            }

            public string ParameterName
            {
                get { return string.Format("@{0}", name); }
            }

            public string Name
            {
                get { return name; }
            }

            public object Value
            {
                get { return value; }
            }
        }
    }
}